﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MvcMusicStore.ViewModels;
using MvcMusicStore.Models;
using DNA.Mvc.DynamicUI;

namespace MvcMusicStore.Controllers
{
    public class StoreController : Controller
    {
        MusicStoreEntities storeDB = new MusicStoreEntities();

        //
        // GET: /Store/
        [SiteMapAction(Title="store")]
        public ActionResult Index()
        {
            // Retrieve list of Genres from database
            var genres = from genre in storeDB.Genres
                         select genre.Name;

            // Set up our ViewModel
            var viewModel = new StoreIndexViewModel()
            {
                Genres = genres.ToList(),
                NumberOfGenres = genres.Count()
            };

            // Return the view
            return View(viewModel);
        }

        //
        // GET: /Store/Browse?Genre=Disco
        [SiteMapAction(Title="genre",
            ShowInMenu=false,
            IsShared=true,
            IgnoreRouteDataKeys=new string[]{"genre"})]
        public ActionResult Browse(string genre)
        {
            // Retrieve Genre and its Associated Albums from database
            var genreModel = storeDB.Genres.Include("Albums")
                .Single(g => g.Name == genre);

            var viewModel = new StoreBrowseViewModel()
            {
                Genre = genreModel,
                Albums = genreModel.Albums.ToList()
            };

            return View(viewModel);
        }

        //
        // GET: /Store/Details/5

        public ActionResult Details(int id)
        {
            var album = storeDB.Albums.Single(a => a.AlbumId == id);

            return View(album);
        }

        //
        // GET: /Store/GenreMenu

        //[ChildActionOnly]
        [Widget("GenreMenu",Category="MusicStore")]
        public ActionResult GenreMenu()
        {
            var genres = storeDB.Genres.ToList();

            return View(genres);
        }

        [Widget("TopSellingAlbums",Category = "MusicStore")]
        [Property("Count",ValueType=typeof(int),DefaultValue=5)]
        public ActionResult TopSellingAlbums(int count)
        {
            // Get most popular albums
            var albums = GetTopSellingAlbums(count);

            return View(albums);
        }

        private List<Album> GetTopSellingAlbums(int count)
        {
            // Group the order details by album and return
            // the albums with the highest count
            
            return storeDB.Albums
                .OrderByDescending(a => a.OrderDetails.Count())
                .Take(count)
                .ToList();
        }
    }
}
